import React, { Component } from 'react';
import { Dialog, Button, Form, Input, Field, TreeSelect, Select } from '@alifd/next';
import { areas } from '../../../../api/Area';
import { Forest } from '../../../../libs/Tree';

const FormItem = Form.Item;

export default class EditDialog extends Component {
  static displayName = 'EditDialog';

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      dataIndex: null,
    };
    this.field = new Field(this);
  }
 componentWillMount() {
   const record = this.props.record;
   this.oth_fields = {
    type: record.type === null ? 0 : record.type,
    name: record.name,
    areaId: record.areaId,
  };
 }
  
 handleSubmit = () => {
    this.field.validate((errors, values) => {
      if (errors) {
        console.log('Errors in form!!!');
        return;
      }
      const { dataIndex } = this.state;
      values.type = this.oth_fields.type;
      values.areaId = this.oth_fields.areaId;
      if (values.useable === undefined){
        values.useable = 0;
      }
      this.props.getFormValues(dataIndex, values);
      this.setState({
        visible: false,
      });
    });
  };

  onOpen = (index, record) => {
    areas().then((areaResp) => {
      const area = areaResp.data.data;
      const areaShow = [];
      area.forEach((ele) => {
        areaShow.push(
          {
              label: ele.name,
              key: ele.id,
              pid: ele.parentId,
              id: ele.id,
              value: ele.id,
          }
        );
      const keys = Object.keys(record);
      keys.forEach((key) => {
        if (record[key] === null){
          record[key] = undefined;
        }
      });
      this.field.setValues({ ...record });
        const areaTree = this.dataToTree(areaShow);
        this.setState({
          dataIndex: index,
          areaSource: areaTree,
          visible: true,
        });
      });
    });
  };

  onClose = () => {
    this.setState({
      visible: false,
    });
  };

  dataToTree= (dataSource) => {
    const forest = new Forest();
    dataSource.forEach((menu) => {
        menu.pid = menu.pid;
        menu.children = [];
        forest.init(menu);
    });
    return forest.roots;
  }

  handleAreaChange = (value) => {
    this.oth_fields.areaId = value;
  }

  onSelectChange =(value) => {
    this.oth_fields.type = value;
  }

  render() {
    const init = this.field.init;
    const { index, record } = this.props;
    const formItemLayout = {
      labelCol: {
        fixedSpan: 6,
      },
      wrapperCol: {
        span: 14,
      },
    };

    const Option = Select.Option;
    const type = record.type;
    const areaId = this.oth_fields.areaId + '';
    return (
      <div style={styles.editDialog}>
        <Button type="primary" size="small" onClick={() => this.onOpen(index, record)}>
        编辑
        </Button>
        <Dialog
          style={{ width: 640 }}
          visible={this.state.visible}
          onOk={this.handleSubmit}
          closeable="esc,mask,close"
          onCancel={this.onClose}
          onClose={this.onClose}
          title="编辑"
        >
          <Form field={this.field}>
            <FormItem label="机构名称：" {...formItemLayout}>
              <Input
                {...init('name', {
                  rules: [{ required: true, message: '必填选项' }],
                })}
              />
            </FormItem>

            <FormItem label="机构类型：" {...formItemLayout}>
              <Select id="basic-demo" onChange={this.onSelectChange} defaultValue={type}>
                <Option value="0">机构</Option>
                <Option value="1">部门</Option>
              </Select>
            </FormItem>

            <FormItem label="所属区域：" {...formItemLayout}>
              <TreeSelect treeDefaultExpandAll 
                dataSource={this.state.areaSource} 
                onChange={this.handleAreaChange} 
                value={areaId}
                style={{ width: 220 }} 
              />
            </FormItem>
          </Form>
        </Dialog>
      </div>
    );
  }
}

const styles = {
  editDialog: {
    display: 'inline-block',
    marginRight: '5px',
  },
};
